const mongoose = require('mongoose');
let orderModel = mongoose.model('orderModel');
let userModel = mongoose.model('userModel');
//查询所有订单
module.exports.getOrders = async function({pageSize,currentPage,merchantId}){
    //总条数
    //let all = await orderModel.find({merchantId:merchantId});
    let all = await orderModel.find();
    let total = all.length;
    //获取最大的页数
    let pages = Math.ceil(total / pageSize);
    //判断当前页是否超出最大范围
    if( currentPage > pages ){
        currentPage = pages;
    }    
    //获取所有符合要求的数据
    let rows = await orderModel.find({merchantId:merchantId})
    .populate('userId')
    .populate('shopId')
    .populate('commodityId')
    .limit(pageSize - 0)   //返回前端几条数据，里面是一个number
    .skip( (currentPage - 1) * pageSize ); //跳页
    
    return {total, rows, pages, pageSize, currentPage};
}
//查询一条订单的数据
module.exports.getOneOrder = async function(p){
    let data = await orderModel.find(p)
    .populate('userId')
    .populate('shopId')
    .populate('commodityId');
    return data;
}
//修改订单信息
module.exports.updateOrders = async function(p){
    let data1 = await orderModel.update({_id:p._id},
        { ...p });
         let data2 = await userModel.update({_id:p.userId._id},
             {...p.userId});
        if(data1&&data2){
            return true;
        }
    return false;   
}
//删除订单
module.exports.deleteOrders = async function(_id){
    let data = await orderModel.deleteOne(_id);
    return data;
}